package cn.tellfish.studydemo.demo.nio;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class BioServer {

    static final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(200, 200, 60,
            TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

    public static void main(String[] args) {
        ServerSocket serverSocket = null;

        try {
            serverSocket = new ServerSocket(8080);
            System.out.printf(Thread.currentThread().getName() + "启动 8080");
            while (true) {
                Socket socket = serverSocket.accept();
                threadPoolExecutor.execute(new SocketProcessor(socket));
                System.out.println("有新的链接啦，当前线程数量" + threadPoolExecutor.getActiveCount());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    static class SocketProcessor implements Runnable {

        private final Socket socket;

        public SocketProcessor(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {

            byte[] requestBody = new byte[1024];
            try {
                socket.setSoTimeout(1000_000);
                socket.getInputStream().read(requestBody);
                String request = new String(requestBody);
                System.out.println("收到数据，当前线程数：" + BioServer.threadPoolExecutor.getActiveCount() +
                        "请求内容:\n" + request);
                socket.getOutputStream().write(("return:" + System.currentTimeMillis()).getBytes());
                socket.getOutputStream().flush();
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                BioServer.threadPoolExecutor.execute(new SocketProcessor(socket));
            }


        }
    }

}
